import { shopStatReturnProductAnalysis } from '../../services/API';
import echarts from './echarts';
import { formatCurrency } from '../../utils/utils';
// function paddingName(name, len) {
//   if (name.length >= len) return name;
//   return name + new Array(len - name.length + 1).join('  ');
// }
export default async function (chartPanel) {
  if (!chartPanel) return;
  try {
    chartPanel.toggleLoading(true);
    const resp = await shopStatReturnProductAnalysis();
    if (!chartPanel) return;
    if (resp.data.length === 0) {
      chartPanel.toggleIsEmpty(true);
      return;
    }
    console.log(resp);
    const data = [];
    let sum = 0;
    let sumValue = 0;
    resp.data.forEach(el => {
      data.push({
        name: el.productName,
        value: el.value,
        money: Number(el.money)
      });
      sum += Number(el.money);
      sumValue += el.value;
    });
    let nameObj = {};
    data.forEach(el => {
      nameObj[el.name] = `${parseInt((el.value / sumValue) * 100)}%  ${formatCurrency(el.money)}`;
    });
    var chartDom = chartPanel.getChartContainer();
    var myChart = echarts.init(chartDom);
    var option = {
      title: {
        text: `Total return ${formatCurrency(sum)}`,
        textStyle: {
          fontSize: 14
        },
        left: 10
      },
      tooltip: {
        trigger: 'item',
        padding: 5,
        position: 'right',
        textStyle: {
          fontSize: 10
        },
        formatter: '{b}: {d}%'
      },
      legend: {
        type: 'scroll',
        orient: 'vertical',
        right: 10,
        top: 20,
        bottom: 20,
        formatter(name) {
          return `${name} | ` + nameObj[name];
        }
      },
      series: [
        {
          name: 'Return reason',
          type: 'pie',
          radius: ['50%', '80%'],
          center: ['35%', '50%'],
          avoidLabelOverlap: false,
          selectedMode: 'single',
          select: {
            label: {
              show: true,
              formatter: '{b}: {d}%'
            }
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: false,
              formatter: '{b}: {d}%'
            }
          },
          labelLine: {
            show: false
          },
          data
        }
      ]
    };
    myChart.setOption(option);
  } catch (err) {
    console.log(err);
  } finally {
    chartPanel.toggleLoading(false);
  }
}
